package com.fouram.core.utils;

import com.google.common.collect.Maps;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import lombok.SneakyThrows;

import java.util.Map;

/**
 * QLExpress工具类（动态脚本引擎解析工具）
 * 参考：https://blog.csdn.net/xiaofeng10330111/article/details/134363363
 * 
 * @author liup
 */
public class QLExpressUtils {

    @SneakyThrows
    public static Object execute(String expression, DefaultContext<String, Object> context){
        // 创建 QLExpress 引擎
        ExpressRunner runner = new ExpressRunner();
        return runner.execute(expression, context, null, true, false);
    }

    public static void main(String[] args) {
        DefaultContext<String, Object> context = new DefaultContext<>();
        context.put("amount", 1000);
        context.put("discount", 0.1);
        // 执行脚本
        String expression = "amount * (1 - discount)";
        System.out.println(execute(expression, context));


        context = new DefaultContext<>();
        Map<String, Number> map = Maps.newHashMap();
        map.put("amount", 1000);
        map.put("discount", 0.1);
        context.put("param", map);
        // 执行脚本
        expression = "param.amount * (1 - param.discount)";
        System.out.println(execute(expression, context));
    }

}
